package com.jwgf.can;

import com.jwgf.comlibrary.CANManager;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * Created by Jacky on 2017/12/28.
 */

public class CanThread {
    private static final CanThread ourInstance = new CanThread();
    private static Disposable disposable;

    public static int timeout = 0;

    private static boolean canState = false;

    private CanThread() {
    }

    public static CanThread getInstance() {
        if (disposable == null || disposable.isDisposed()) {
            disposable = createDisposable();
        }

        return ourInstance;
    }

    public boolean canState() {
        return canState;
    }

    private static Disposable createDisposable() {
        return Observable.just(1)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Throwable {
                        while (true) {
                            byte[] data = CANManager.getInstance().read1();

                            if (data != null) {
                                timeout = 0;
                                canState = true;
                                if (EventBus.getDefault().hasSubscriberForEvent(CanMessage.class)) {
                                    EventBus.getDefault().post(new CanMessage(data));
                                }
                            } else {
                                ++timeout;
                                if (timeout > 60 * 2000) {
                                    timeout = 0;
                                    canState = false;
                                    CANManager.getInstance().reset1();
                                }
                                try {
                                    Thread.sleep(1);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
    }

}
